import { useEffect } from 'react';
import {useLocation, Navigate} from 'react-router-dom';
import { whiteList } from './routes.tsx';
import {Auth} from "../type/Auth.ts";

const AuthInterceptor = ({ children }) => {
    const location = useLocation();
    const token = localStorage.getItem(Auth.TOKEN);

    // 白名单路径检查
    const isWhiteList = whiteList.some(path =>
        location.pathname.startsWith(path)
    );

    // 自动清理授权状态
    useEffect(() => {
        return () => {
            if (location.pathname !== '/auth/callback') {
                localStorage.removeItem(Auth.STATE);
            }
        };
    }, [location]);

    // 白名单路径直接放行
    if (isWhiteList) {
        return children;
    }

    return token ? children : <Navigate to="/login"/>;
};

export default AuthInterceptor;
